/**
 * 首页路由
 */

var router = require('express').Router();
var articleTool = require('../bin/article');
var datetimeTool = require('../bin/util/datetime');
var heatQuery = require('../bin/heatQuery');
var blockTool = require('../bin/block')

var indexRouter = async function(req, res) {
    if (req.url === '/' && req.originalUrl[req.originalUrl.length-1] !== '/'){
        res.redirect(req.originalUrl + '/');
        return;
    }
    res.locals.blocksDic = blockTool.getBlocksDic(res.locals.blocks, true);

    let appendFilter = {};
    if (res.locals.block)
        appendFilter.mainclass = { $regex: '^('+res.locals.block+'(/.*)?)?$' };

    let isAdmin = 'user' in req.session && (req.session.user.role === 'admin' || req.session.user.role === 'admin:'+res.locals.blockRoot);
    if (!isAdmin)
        appendFilter.status = {$ne:1};

    let isSuperAdmin = isAdmin && req.session.user.role === 'admin';

    let docs = await heatQuery.getQuery(new Date().getTime(), appendFilter);

    let local = { isAdmin, isSuperAdmin, articles : docs.map((doc) => {
            let article = articleTool.toLocal(doc);
            articleTool.setBadge(article);
            if (typeof(article.publish) === 'number')
                article.publish = datetimeTool.to_yMdHm(article.publish).substr(5);
            return article;
        })
    };

    res.render('dyn.index.html', local);
};

router.get('/', indexRouter);

router.get('/index(.*)?', indexRouter);

module.exports = router;